<template>
  <div class="assetList-root">
    <lark-drawer border title="种质资源库列表" title-height="40px" width="420px">
      <div class="asset-drawer-content">
        <div class="operation-root">
          <div class="input-search">
            <el-input v-model="filterText" size="mini" placeholder="输入名称进行搜索" @keyup.enter.native="filterAction">
              <el-button @click="filterAction" slot="append" size="mini" icon="el-icon-search"></el-button>
            </el-input>
          </div>
          <div class="add-btn">
            <el-button size="mini" @click="addRootNodeBtn(0,'顶级节点')">新增</el-button>
          </div>
        </div>
        <el-scrollbar>
          <div v-loading="treeLoading" class="tree-root">
            <el-tree ref="tree" :filter-node-method="filterNode" :expand-on-click-node="false" :default-expand-all="false" :data="treeData"
                     :props="defaultProps" @node-click="handleNodeClick">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span class="tree-node-operation" @click.stop="()=>{}">
                 <el-dropdown trigger="click">
                    <div>
                      <i class="fa fa-ellipsis-v" aria-hidden="true"></i>
                    </div>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-if="data.type != '6'" icon="el-icon-plus" @click.native="addLeafNodeData(node,data)">新增</el-dropdown-item>
                      <el-dropdown-item icon="el-icon-edit" @click.native="updateLeafNodeData(node,data)">修改</el-dropdown-item>
                      <el-dropdown-item icon="el-icon-delete" @click.native="deleteNodeData(node,data)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </span>
              </span>
            </el-tree>
          </div>
        </el-scrollbar>
      </div>
    </lark-drawer>
    <lark-card border :card-title="addNodeForm.id == null?'新增':'编辑'" :x="500" :radius="false" v-if="addNodeVisible" :hidden="!addNodeVisible"
               body-width="400px" body-height="300px"
               @closeAction="addNodeVisible = !addNodeVisible" draggable>
      <div class="add-node-root">
        <el-form ref="add-node-form" :model="addNodeForm" label-width="80px" :rules="rules">
          <el-form-item label="上级资源" v-show="addNodeForm.id == null">
            {{ currentNodeName }}
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="addNodeForm.type" :disabled="addNodeForm.parentId == 0">
              <el-option v-for="(item,index) in nodeType" :key="index" :value="item.dictValue" :label="item.dictLabel"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input placeholder="请输入名称" v-model="addNodeForm.name"></el-input>
          </el-form-item>

          <el-form-item label="位置" v-show="addNodeForm.type == 1">
            <el-col :span="9">
              <el-input v-model="addNodeForm.x" placeholder="经度"></el-input>
            </el-col>
            <el-col style="text-align: center" :span="2">-</el-col>
            <el-col :span="9">
              <el-input v-model="addNodeForm.y" placeholder="维度"></el-input>
            </el-col>
            <el-col :span="4">
              <el-button size="mini" type="text" @click="selectPosition">选择</el-button>
            </el-col>
          </el-form-item>

          <el-form-item>
            <div class="add-node-form-submit">
              <el-button @click="submitAddNodeForm">确定</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </lark-card>
  </div>
</template>

<script>
import { reactive, toRefs, onMounted, ref, watch, computed, nextTick } from '@vue/composition-api'
import { shelveList, addShelve, delShelve, updateShelve } from '@/api/industry/gpm'
import { getDicts } from '@/api/system/dict/data'
import { handleTree } from '@/utils/mc.js'
import { Message, MessageBox } from 'element-ui'
import { draw, clearDrawGeometry } from 'lark-map'

export default {
  name: 'assetList',
  props: {
    mapView: {
      type: Object,
      default() {
        return null
      }
    }
  },
  setup(props, content) {
    let data = reactive({
      treeLoading: false,
      pubOperationCb: null,//从外部调用增加、删除、修改的回调方法
      treeData: [],
      filterText: null,
      nodeType: [],
      addNodeVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ]
      },
      currentNodeName: null,
      addNodeForm: {
        id: null,
        name: null,
        type: null,
        parentId: null,
        x: null,
        y: null
      },
      currentOperationNode: null
    })

    watch(() => data.filterText, () => {
      filterAction()
    })
    const selectPosition = async() => {
      let graphic = await draw({ type: 'point', view: props.mapView })
      let { geometry: { x, y } } = graphic
      data.addNodeForm.x = x
      data.addNodeForm.y = y

      clearDrawGeometry({ view: props.mapView })
    }

    const handleNodeClick = (data) => {
      content.emit('nodeClick', data)
    }
    const deleteNodeData = async(node, data) => {
      MessageBox.confirm(`确定删除 ${data.name} `, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delShelve(data.id)
        reloadLayer()
        const parent = node.parent
        const children = parent.data.children || parent.data
        const index = children.findIndex(d => d.id === data.id)
        children.splice(index, 1)
        Message.success('删除成功')
      }).catch(() => {
      })
    }
    const filterAction = () => {
      content.refs.tree.filter(data.filterText)
    }
    const filterNode = (value, da) => {
      if (!value) return true
      return da.name.indexOf(value) !== -1
    }
    const loadTreeData = async() => {
      let response = await shelveList()
      let result = handleTree(response.data)
      data.treeData = result
    }
    const resetAddNodeForm = () => {
      data.currentNodeName = null
      data.addNodeForm = {
        id: null,
        name: null,
        type: null,
        parentId: null,
        x: null,
        y: null
      }
      data.currentOperationNode = null
    }
    const addRootNodeBtn = (parentId, currentNodeName) => {
      resetAddNodeForm()
      data.addNodeForm.parentId = parentId
      if (parentId == 0) {
        data.addNodeForm.type = '1'
      }
      data.currentNodeName = currentNodeName
      data.addNodeVisible = true
    }
    const addLeafNodeData = (node, da) => {
      resetAddNodeForm()
      data.currentOperationNode = da
      data.currentNodeName = da.name
      data.addNodeForm.parentId = da.id
      data.addNodeVisible = true
      if (node) {
        node.expanded = true
      }
    }

    const findNodeById = (id, treeData) => {
      for (let i = 0; i < treeData.length; i++) {
        let td = treeData[i]
        if (td.id == id) {
          return td
        }
        if (td.children) {
          let res = findNodeById(id, td.children)
          if (res != null) {
            return res
          }
        } else {
        }

      }
    }

    const addNodePub = (id, cb) => {
      data.pubOperationCb = cb
      let nodeData = findNodeById(id, data.treeData)
      addLeafNodeData(null, nodeData)
    }

    const updateLeafNodeData = (node, da) => {
      resetAddNodeForm()
      data.currentOperationNode = da
      data.currentNodeName = da.name
      data.addNodeForm.parentId = da.parentId
      data.addNodeForm.type = da.type
      data.addNodeForm.name = da.name
      data.addNodeForm.id = da.id
      if (da.x) {
        data.addNodeForm.x = da.x
      }
      if (da.y) {
        data.addNodeForm.y = da.y
      }
      data.addNodeVisible = true
    }
    const reloadLayer = () => {
      props.mapView.map.findLayerById('GpmBlankService').refresh()
    }
    const submitAddNodeForm = async() => {
      try {
        content.refs['add-node-form'].validate(async(valid) => {
          if (valid) {
            if (data.addNodeForm.type == 1 && (data.addNodeForm.x == null || data.addNodeForm.y == null)) {
              Message.error('位置不能为空')
              return
            }
            if (data.addNodeForm.type != 1) {
              data.addNodeForm.x = null
              data.addNodeForm.y = null
            }
            let response = null
            data.treeLoading = true
            if (data.addNodeForm.id == null) {
              response = await addShelve(data.addNodeForm)
            } else {
              response = await updateShelve(data.addNodeForm)
            }
            reloadLayer()

            data.addNodeVisible = false
            if (data.addNodeForm.id == null) {
              if (data.currentOperationNode == null) {
                data.treeData.push(response.data)
              } else {
                data.currentOperationNode.children.push(response.data)
              }
            } else {
              data.currentOperationNode.type = response.data.type
              data.currentOperationNode.name = response.data.name
            }
            Message.success(data.addNodeForm.id != null ? '修改成功' : '添加成功')
            if (data.pubOperationCb) {
              data.pubOperationCb()
            }
          }
        })
      } finally {
        data.treeLoading = false
      }
    }
    const loadNodeType = async() => {
      let response = await getDicts('sys_shelve_type')
      data.nodeType = response.data
    }
    onMounted(() => {
      loadTreeData()
      loadNodeType()
    })
    return {
      ...toRefs(data),
      reloadLayer,
      selectPosition,
      addNodePub,
      handleNodeClick,
      deleteNodeData,
      filterNode,
      filterAction,
      loadTreeData,
      addRootNodeBtn,
      resetAddNodeForm,
      addLeafNodeData,
      submitAddNodeForm,
      updateLeafNodeData
    }
  }
}


</script>

<style scoped lang="scss">
.assetList-root {
  .asset-drawer-content {
    height: 50vh;
    overflow: hidden;
  }

  .tree-root {
    padding: 5px 10px;
    height: calc(50vh - 50px);

    .custom-tree-node {
      width: 100%;
      position: relative;

      .tree-node-operation {
        position: absolute;
        right: 10px;
      }
    }
  }

  .operation-root {
    padding: 0px 10px;
    height: 50px;
    line-height: 50px;
    display: flex;
    flex-direction: row;
    border-bottom: 1px dashed green;

    .add-btn {
      padding: 0 10px;
    }

    .input-search {
      flex: 1 0;
    }
  }
}
</style>
<style lang="scss">
.add-node-root {
  padding: 20px;

  .add-node-form-submit {
    width: 100%;
    text-align: right;
  }
}

.assetList-root {
  .el-tree {
    background-color: transparent;

    .el-dropdown {
      width: 30px;
      text-align: center;
    }
  }
}

</style>
